package com.yun.jing.common.filter;

import com.yun.jing.common.config.jwt.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author: Wang
 * Jwt的过滤器 用于对token的验证
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    private JwtTokenUtils jwtTokenUtils;

    public JwtAuthenticationTokenFilter(JwtTokenUtils jwtTokenUtils) {
        this.jwtTokenUtils = jwtTokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException, IOException, ServletException {
         System.out.println("Jwt过滤器");
        String requestRri = httpServletRequest.getRequestURI();
        String token = null;

        String bearerToken = httpServletRequest.getHeader("token");
        String url= httpServletRequest.getRequestURI();
//
//        if ("/server/login".equals(url)){
//            System.out.println("登录放行");
//            filterChain.doFilter(httpServletRequest, httpServletResponse);
//            return;
//        }
         System.out.println(bearerToken);
            boolean faly = true;
         if (bearerToken==null)
         {
             faly=false;
         }
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer"+" ")) {
            token = bearerToken.substring("1212121hsodhsdhasdhsaldhsalhdlsahdlsad1685555555555555555555555555555555555555555555555".length());
        }

        if (faly&&jwtTokenUtils.validateToken(bearerToken)) {
            Authentication authentication = jwtTokenUtils.getAuthentication(bearerToken);
            //设置系统登录用户
            SecurityContextHolder.getContext().setAuthentication(authentication);
            log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
        } else {
            log.debug("no valid JWT token found, uri: {}", requestRri);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }


}
